package com.zzy.backend.consumer;

import com.alibaba.fastjson.JSONObject;
import com.zzy.backend.consumer.utils.Game;
import com.zzy.backend.consumer.utils.JwtAuthenticationUtil;
import com.zzy.backend.mapper.RecordMapper;
import com.zzy.backend.mapper.UserMapper;
import com.zzy.backend.pojo.Record;
import com.zzy.backend.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{token}")  // 注意不要以'/'结尾,前端发请求要以/结尾
public class WebSocketServer {
    //并发访问，需要ConcurrentHashMap
    final public static ConcurrentHashMap<Integer,WebSocketServer> users = new ConcurrentHashMap<>();
    //CopyOnWriteArraySet后面了解一下
    final private static CopyOnWriteArraySet<User> matchpool = new CopyOnWriteArraySet<>();
    private User user;
    private Session session = null;
    private Game game = null;

    //因为WebSocketServer与Controller不同，不是单例模式，因此不能直接用Autowired
    private static UserMapper userMapper;
    public static RecordMapper recordMapper;

    /*
        @Autowired写在set()方法上，在spring会根据方法的参数类型从ioc容器中找到该类型的
        Bean对象注入到方法的行参中，并且自动反射调用该方法(被@Autowired修饰的方法一定会
        执行)，所以一般使用在set方法中、普通方法不用。
    */
    @Autowired
    public void setUserMapper(UserMapper userMapper){
        WebSocketServer.userMapper = userMapper;
    }

    @Autowired
    public void setRecordMapper(RecordMapper recordMapper){WebSocketServer.recordMapper = recordMapper;}

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        // 建立连接
        this.session = session;
        System.out.println("connected!");
        Integer userId = JwtAuthenticationUtil.getUserId(token);
        this.user = userMapper.getUser(userId);

        if(user!=null){
            users.put(userId,this);
            System.out.println(this);
        }else{
            this.session.close();
        }

        System.out.println(users);
    }

    @OnClose
    public void onClose() {
        // 关闭链接
        if(this.user!=null){
            users.remove(this.user.getId());
            matchpool.remove(this.user);
        }
        System.out.println("disconnected!");
    }

    private void startMatching() throws InterruptedException {
        matchpool.add(this.user);
        System.out.println(matchpool.size());

        while(matchpool.size() >= 2){
            System.out.println("match_success");
            Iterator<User> it = matchpool.iterator();
            User a = it.next(), b = it.next();
            matchpool.remove(a);
            matchpool.remove(b);

            Game game = new Game(13,14,20,a.getId(),b.getId());
            game.createMap();
            //把不同的比赛放入不同的线程，这样匹配和不同的比赛可以同时进行
            game.start();

            users.get(a.getId()).game = game;
            users.get(b.getId()).game = game;

            JSONObject respGame = new JSONObject();
            respGame.put("a_id",game.getPlayerA().getId());
            respGame.put("a_sx",game.getPlayerA().getSx());
            respGame.put("a_sy",game.getPlayerA().getSy());
            respGame.put("a_steps",game.getPlayerA().getSteps());
            respGame.put("b_id",game.getPlayerB().getId());
            respGame.put("b_sx",game.getPlayerB().getSx());
            respGame.put("b_sy",game.getPlayerB().getSy());
            respGame.put("b_steps",game.getPlayerB().getSteps());
            respGame.put("map",game.getG());

            //给A传B，给B传A
            JSONObject respA = new JSONObject();
            respA.put("event","start-matching");
            respA.put("opponent_username",b.getUsername());
            respA.put("opponent_photo",b.getPhoto());
            respA.put("game",respGame);

            users.get(a.getId()).sendMessage(respA.toJSONString());

            JSONObject respB = new JSONObject();
            respB.put("event","start-matching");
            respB.put("opponent_username",a.getUsername());
            respB.put("opponent_photo",a.getPhoto());
            respB.put("game",respGame);
            /*
                不加下面这行sleep语句的话使用同一浏览器打开两个窗口调试会报错，原因可能是
                浏览器不同的websocket连接是多线程的，上一个线程还在接收服务器数据的时候
                这个线程是不能响应的，因此从users中获取websocket会报空指针异常
            */
            //Thread.sleep(1000);
            users.get(b.getId()).sendMessage(respB.toJSONString());
        }
    }

    private void stopMatching(){
        matchpool.remove(this.user);
    }

    private void move(int direction){
        if(game.getPlayerA().getId().equals(user.getId())){
            game.setNextStepA(direction);
        }else if(game.getPlayerB().getId().equals(user.getId())){
            game.setNextStepB(direction);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) throws InterruptedException { //当做路由
        // 从Client接收消息，起到转发效果
        System.out.println("receive message!");
        JSONObject data = JSONObject.parseObject(message);
        String event = data.getString("event");
        if("start-matching".equals(event)){
            System.out.println(event);
            startMatching();
        }else if("stop-matching".equals(event)){
            System.out.println(event);
            stopMatching();
        }else if("move".equals(event)){
            move(data.getInteger("direction"));
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessage(String message){
        synchronized (this.session){
            try {
                this.session.getBasicRemote().sendText(message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
